"""
音频处理API路由
"""
import os
from typing import List
import uuid

from fastapi import APIRouter, Depends, File, UploadFile, Form, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
from loguru import logger

from app.core.cos_client import cos_manager
from app.databases.database import get_async_db
from app.api.deps import get_async_audio_service
from app.databases.schemas import (
    AudioProcessingResponse,
    AudioProcessingRecord
)
from app.core.exceptions import (
    AudioProcessingException,
    InvalidPitchStepsException,
    UnsupportedFileTypeException
)

router = APIRouter()


@router.post("/pitch-shift", response_model=AudioProcessingResponse)
async def pitch_shift_audio(
    audio_file: UploadFile = File(..., description="上传的音频文件"),
    n_steps: int = Form(..., description="音调调节的半音数，范围-24到24"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    音频升降调处理接口
    
    Args:
        audio_file: 上传的音频文件
        n_steps: 音调调节的半音数，范围-24到24
        db: 数据库会话
    
    Returns:
        AudioProcessingResponse: 处理结果
    """
    try:
        # 获取音频处理服务
        audio_service = await get_async_audio_service(db)
        # 处理音频
        processed_audio, result_info = await audio_service.process_audio(
            audio_file, n_steps
        )

        # 生成唯一文件名
        original_filename = audio_file.filename or "audio"
        name, ext = os.path.splitext(original_filename)
        output_filename = f"{name}_pitch_shifted_{n_steps}steps_{uuid.uuid4().hex}.wav"

        # 上传音频数据
        file_url = cos_manager.upload_audio_bytes(processed_audio, output_filename)

        audio_info = audio_service.get_audio_info(processed_audio)

        # 返回响应
        return AudioProcessingResponse(
            record_id=result_info["record_id"],
            filename=result_info["filename"],
            processing_time=result_info["processing_time"],
            status=result_info["status"],
            message="音频处理成功",
            file_url=file_url,
            audio_info=audio_info
        )
        
    except InvalidPitchStepsException:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="音调步数必须在-24到24之间"
        )
    except UnsupportedFileTypeException:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不支持的文件类型，请上传音频文件"
        )
    except AudioProcessingException as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"处理失败: {str(e)}"
        )


@router.get("/records", response_model=List[AudioProcessingRecord])
async def get_processing_records(
    limit: int = 10,
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取最近的处理记录
    
    Args:
        limit: 记录数量限制
        db: 数据库会话
    
    Returns:
        List[AudioProcessingRecord]: 处理记录列表
    """
    audio_service = await get_async_audio_service(db)
    records = await audio_service.get_recent_records(limit)
    
    return [
        AudioProcessingRecord(
            id=record["id"],
            filename=record["filename"],
            file_size=0,  # 这里可以扩展获取文件大小
            file_type="audio/wav",
            pitch_steps=record["pitch_steps"],
            processing_time=record["processing_time"],
            status=record["status"],
            created_at=record["created_at"]
        )
        for record in records
    ]


@router.get("/records/{record_id}", response_model=AudioProcessingRecord)
async def get_processing_record(
    record_id: int,
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取指定的处理记录
    
    Args:
        record_id: 记录ID
        db: 数据库会话
    
    Returns:
        AudioProcessingRecord: 处理记录详情
    """
    audio_service = await get_async_audio_service(db)
    record = await audio_service.get_processing_record(record_id)
    
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="记录不存在"
        )
    
    return AudioProcessingRecord(**record)


@router.get("/statistics")
async def get_processing_statistics(
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取处理统计信息
    
    Args:
        db: 数据库会话
    
    Returns:
        dict: 统计信息
    """
    audio_service = await get_async_audio_service(db)
    return await audio_service.get_statistics()


@router.post("/info")
async def get_audio_info(
    audio_file: UploadFile = File(..., description="音频文件"),
    db: AsyncSession = Depends(get_async_db)
):
    """
    获取音频文件信息
    
    Args:
        audio_file: 音频文件
        db: 数据库会话
    
    Returns:
        dict: 音频信息
    """
    try:
        audio_service = await get_async_audio_service(db)
        audio_data = await audio_file.read()
        
        info = audio_service.get_audio_info(audio_data)
        
        return {
            "filename": audio_file.filename,
            "file_size": len(audio_data),
            "content_type": audio_file.content_type,
            "audio_info": info
        }
        
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取音频信息失败: {str(e)}"
        )
